# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'DFSX10010038': {  # 快来付 支付宝wap 2.4% 20-20000 loki
        'API_KEY': '8224ee62ff367efaa11bb9b69701f3ca',
        'gateway': 'http://47.75.62.198:7071/pay/cnp/gateway',
        'query_gateway': 'http://47.75.62.198:7071/pay/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_org_no(mch_id):
    return APP_CONF[mch_id]['org_no']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("kuailaifupay notify sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '20000'
    return '20000'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('merchant_no', str(app_id)),
        ('amount', '%.2f' % pay_amount),
        ('currency', '156'),
        ('order_no', str(pay.id)),
        ('pay_code', _get_pay_type(service)),
        ('pay_ip', _get_device_ip(info)),
        ('request_time', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('product_name', 'kuailaifupay'),
        ('return_url',
         '{}/pay/api/{}/kuailaifupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notify_url', '{}/pay/api/{}/kuailaifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('remark', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("kuailaifupay create: %s, order_is is: %s", json.dumps(parameter_dict), parameter_dict['order_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("kuailaifupay create: response: %s", response.text)
    data = json.loads(response.text)
    return {'charge_info': data['data']}


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("kuailaifupay notify data: %s, order_id is: %s", data, data['order_no'])
    verify_notify_sign(data, api_key)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('kuailaifupay event does not contain pay ID')
    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)
    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['ord_status'])
    trade_no = data['order_no']
    total_fee = float(data['order_amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS' and total_fee > 0.0:
        _LOGGER.info('kuailaifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant_no', app_id),
        ('order_no', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("kuailaifupay query url: %s, %s, order_is is: %s", _get_query_gateway(app_id),
                 json.dumps(parameter_dict), parameter_dict['order_no'])
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("kuailaifupay query response: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['ord_status'])
        total_fee = float(data['pay_amount'])
        trade_no = data['order_no']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == 'SUCCESS':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('kuailaifupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
